package com.h3bpm.starcharge.controller.k3c;

import java.text.SimpleDateFormat;
import java.util.*;


import OThinker.Common.Data.BoolMatchValue;
import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.H3.Entity.Data.Attachment.Attachment;
import OThinker.H3.Entity.Data.Attachment.AttachmentHeader;
import OThinker.H3.Entity.Instance.Data.IInstanceDataItem;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.starcharge.bean.k3c.MaterialBase;
import com.h3bpm.starcharge.common.uitl.SqlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.h3bpm.starcharge.common.bean.JsonResult;
import com.h3bpm.starcharge.common.uitl.ErrorUtil;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.service.k3c.K3cMaterialService;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/k3c/procurement")
public class ProcurementController extends ControllerBase{

	@Autowired
	private K3cMaterialService k3cMaterialService;

	@Value("${orderFormJson}")
	private String orderFormJson;

	@Value("${FPOOrderEntry}")
	private String fpOrderEntity;

    @Value("${PurchaseRequestParam}")
    private String purchaseRequestParam;
    
    @Value("${formJson}")
    private String formJson;

    @Value("${fEntity}")
    private String fEntity;

    @Value("${payAppOrder}")
    private String payAppOrder;

	@Value("${FPAYAPPLYENTRY}")
	private String fPayApplyEntity;

	@Value("${Receiving}")
    private String receiving;
    
    @Value("${FDetailEntity}")
    private String fDetailEntity;

	@Value("${APpayableOrder}")
	private String aPpayableOrder;

	@Value("${FEntityDetail}")
	private String fEntityDetail;

	@Override
	public String getFunctionCode() {
		// TODO Auto-generated method stub
		return null;
	}





	public   JsonResult<K3cBase> push(JSONArray numbers ,String targetFormId,String ruleId) throws Exception{
		JSONObject  json = new JSONObject();
		String[] rule=ruleId.split("-");
    	json.put("Numbers",numbers);
    	json.put("RuleId", ruleId);
    	json.put("TargetFormId", rule[1]);
    	json.put("IsEnableDefaultRule", "true");
    	json.put("IsDraftWhenSaveFail", "false");
	    JsonResult<K3cBase> pushResult = k3cMaterialService.push(targetFormId, json.toString());
	    if("500".equals(pushResult.getCode().toString())) {
	    	throw new Exception("500");
	    }
		return pushResult;

	}


	public   JsonResult<K3cBase> savePush(JSONArray numbers ,String targetFormId,String ruleId) throws Exception{
		JSONObject  json = new JSONObject();
		String[] rule=ruleId.split("-");
		json.put("Numbers",numbers);
		json.put("RuleId", ruleId);
		json.put("TargetFormId", rule[1]);
		json.put("IsEnableDefaultRule", "true");
		json.put("IsDraftWhenSaveFail", "true");
		JsonResult<K3cBase> pushResult = k3cMaterialService.push(targetFormId, json.toString());
		if("500".equals(pushResult.getCode().toString())) {
			 throw new Exception("500");
		}
		return pushResult;

	}



	public Map<String,String> deleteOrder(Map<String,String> orderNumber)  {

             for(String key : orderNumber.keySet()) {
            	 if("无".equals(orderNumber.get(key).toString())) {

            	 }else {
            		 JSONObject procurement = new JSONObject();
				 JSONArray procurementArray= new JSONArray();
				 procurementArray.add( orderNumber.get(key));
				 procurement.put("Numbers",  procurementArray);
				 //反审核
				 System.out.println("反审核"+key+"订单");
				 try {
					 k3cMaterialService.unAudit(key, procurement.toString());
				 } catch (Exception e) {
					 // TODO Auto-generated catch block
					 e.printStackTrace();
				 }
				 System.out.println("删除"+key+"订单");
				 try {
					 k3cMaterialService.delete(key, procurement.toString());
				 } catch (Exception e) {
					 // TODO Auto-generated catch block
					 e.printStackTrace();
				 }
				 orderNumber.put(key,  "反审核删除成功");
			 }
             }
    	return orderNumber;

    }


	/**
	 *  先删除然后反审核
	 * * @param instanceId
	 * @return
	 */
	@RequestMapping(value = "/unDeleteOrderCg" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,Object> deleteUnAOrder(String deleStr,String deleNo,String unStr,String unNo){
		Map<String,Object> map =  new HashMap();
		JSONObject procurement = new JSONObject();
		JSONArray procurementArray= new JSONArray();
		procurementArray.add( deleNo);
		procurement.put("Numbers",  procurementArray);

		System.out.println("删除"+deleNo+"订单");
		try {
			k3cMaterialService.delete(deleStr, procurement.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("message", "删除成功");
		procurement = new JSONObject();
		procurementArray= new JSONArray();
		procurementArray.add(unNo);
		procurement.put("Numbers",  procurementArray);
		//反审核
		System.out.println("反审核"+unNo+"订单");
		try {
			JsonResult<K3cBase> result= k3cMaterialService.unAudit(unStr, procurement.toString());
			map.put("Message",result);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("反审核"+unNo+"订单失败");
			map.put("Message","反审核"+unNo+"订单失败");
		}
		return map;
	}



	/**
	 *  先反审核后删除
	 * * @param instanceId
	 * @return
	 */
	@RequestMapping(value = "/unADeleteOrderCg" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,Object> unADeleteOrder(String deleStr,String deleNo,String unStr,String unNo){
		Map<String,Object> map =  new HashMap();
		JSONObject procurement = new JSONObject();
		JSONArray procurementArray= new JSONArray();
		procurementArray.add(unNo);
		procurement.put("Numbers",  procurementArray);
		//反审核
		System.out.println("反审核"+unNo+"订单");
		try {
			JsonResult<K3cBase> result= k3cMaterialService.unAudit(unStr, procurement.toString());
			map.put("Message",result);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("反审核"+unNo+"订单失败");
			map.put("Message","反审核"+unNo+"订单失败");
		}

		procurement = new JSONObject();
		procurementArray= new JSONArray();
		procurementArray.add( deleNo);
		procurement.put("Numbers",  procurementArray);
		System.out.println("删除"+deleNo+"订单");
		try {
			k3cMaterialService.delete(deleStr, procurement.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("message", "删除成功");
		return map;
	}







	/**
	 *  删除单据+反审核
	 * * @param instanceId
	 * @return
	 */
	@RequestMapping(value = "/unDeleteOrder" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,Object> unDeleteOrder(String orderArray){

		JSONArray a =JSONArray.parseArray(orderArray);
       Map<String,Object> map =  new HashMap();
		for(int i=0;i<a.size();i++){
			JSONObject procurement = new JSONObject();
			JSONArray procurementArray= new JSONArray();
			procurementArray.add( a.getJSONObject(i).getString("orderNo"));
			procurement.put("Numbers",  procurementArray);
			//反审核
			System.out.println("反审核"+a.getJSONObject(i).getString("orderNo")+"订单");
			try {
				k3cMaterialService.unAudit(a.getJSONObject(i).getString("type"), procurement.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("删除"+a.getJSONObject(i).getString("orderNo")+"订单");
			try {
				k3cMaterialService.delete(a.getJSONObject(i).getString("type"), procurement.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			map.put(a.getJSONObject(i).getString("orderNo"),  a.getJSONObject(i).getString("orderNo")+"反审核删除成功");
		}


		return map;
	}


	/**
	 *  删除单据
	 * * @param instanceId
	 * @return
	 */
	@RequestMapping(value = "/deleteOrder" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,Object> deleteOrder(String key,String orderNo){

		Map<String,Object> map =  new HashMap();

			JSONObject procurement = new JSONObject();
			JSONArray procurementArray= new JSONArray();
			procurementArray.add( orderNo);
			procurement.put("Numbers",  procurementArray);

			System.out.println("删除"+orderNo+"订单");
			try {
				 k3cMaterialService.delete(key, procurement.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			map.put("message", "删除成功");

		return map;
	}



	/**
	 *  反审核单据
	 * * @param instanceId
	 * @return
	 */
	@RequestMapping(value = "/unAuditOrder" , produces = "application/json;charset=utf-8")
	@ResponseBody
    public Map<String,Object> unAuditOrder(String key,String orderNo){
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject procurement = new JSONObject();
		JSONArray procurementArray= new JSONArray();
		procurementArray.add(orderNo);
		procurement.put("Numbers",  procurementArray);
		//反审核
		System.out.println("反审核"+orderNo+"订单");
		try {
			JsonResult<K3cBase> result= k3cMaterialService.unAudit(key, procurement.toString());
			map.put("Message",result);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("反审核"+orderNo+"订单失败");
			map.put("Message","反审核"+orderNo+"订单失败");
		}
            return map;
	}



	/**
	 * 直接提交 付款申请单
	 * * @param instanceId
	 * @param formId
	 * @return
	 */
	@RequestMapping(value = "/savePayOrder" , produces = "application/json;charset=utf-8")
    @ResponseBody
	public Map<String,String> payAppOrder(String instanceId ,String formId,String detailCode){

		 Map<String,String> numbers=new LinkedHashMap<String,String>();
		 numbers.put("AP_PAYBILL", "无");
		 numbers.put("CN_PAYAPPLY", "无");
	     try {

   	  	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       	 @SuppressWarnings("unused")
	   		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
	       	Map<String,Object> procurementValues=instanceData.getBizObject().getValueTable();
	       	String date=format.format(procurementValues.get("applDate"));
	       	System.out.println(date);
       	BizObject[] zbBizObjects = (BizObject[]) procurementValues.get(detailCode);
	       	JSONArray fEntityArray = new JSONArray();
	       	for(int i=0;i<zbBizObjects.length;i++) {
	       		 Map<String, Object> zbValueTable = zbBizObjects[i].getValueTable();

	       		String waitPayDate=format.format(zbValueTable.get("waitPayDate"));
	       		String payDete=format.format(zbValueTable.get("payDete"));
	       		String par = String.format(fPayApplyEntity ,"",zbValueTable.get("costProject"),zbValueTable.get("payType"),zbValueTable.get("payUse"),payDete,waitPayDate,zbValueTable.get("applPayMoney"),zbValueTable.get("FWBXM"));
				fEntityArray.add(par);
	       	}

	       	String param = String.format(payAppOrder,"0",procurementValues.get("billType"),date,procurementValues.get("collUnitType"),procurementValues.get("collUnitType"),procurementValues.get("collUnit"),procurementValues.get("collUnit"), procurementValues.get("currency"),procurementValues.get("applUnit") ,procurementValues.get("applUnit"),procurementValues.get("applUnit"),procurementValues.get("applUnit"),procurementValues.get("currency"));
	           JSONObject jsonParam = JSONObject.fromObject(param);

	           jsonParam.getJSONObject("Model").put("FPAYAPPLYENTRY", fEntityArray);
	           System.out.println(jsonParam.toString());
	    	 		//保存付款申请单
  					JsonResult<K3cBase> kResult=  k3cMaterialService.allSave(formId,jsonParam.toString());
                    if("ok".equals(kResult.getMsg())) {
                   	 numbers.put("CN_PAYAPPLY", kResult.getData().getNumber());
	     }

			 instanceData.getItem("CNPAYAPPLY").setValue(numbers.get("CN_PAYAPPLY"));
			 instanceData.Submit();
	   	return numbers;
			} catch (Exception e) {
				 e.printStackTrace();
				try {
					return	deleteOrder(numbers);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}


		 return null;
	}

	/**
	 *  生成采购订单，下推至收料或入库
	 * @param instanceId
	 * @param detailCode 子表编码
	 * @return
	 */
	public  Map<String,String> purRequisitionOrder( String instanceId,String detailCode){

	Map<String, String> result = new LinkedHashMap<>();
	result.put("CN_PAYAPPLY","无");
	result.put("AP_Payable","无");
	result.put("PUR_ReceiveBill", "无");
	result.put("PUR_PurchaseOrder", "无");
	try {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		@SuppressWarnings("unused")
		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
		String date = format.format(procurementValues.get("FApplicationDate"));
		System.out.println(date);

		BizObject[] zbBizObjects = (BizObject[]) procurementValues.get(detailCode);
		JSONArray fEntityArray = new JSONArray();

		for (int i = 0; i < zbBizObjects.length; i++) {
			Map<String, Object> zbValueTable = zbBizObjects[i].getValueTable();
			String par = String.format(fpOrderEntity,procurementValues.get("FApplicantId"), zbValueTable.get("Fproject"), zbValueTable.get("FMaterialId"), zbValueTable.get("FMaterialName"), zbValueTable.get("FBaseUnitId"), zbValueTable.get("FReqQty"), zbValueTable.get("FBaseUnitId"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"), date, zbValueTable.get("FTaxPrice"),zbValueTable.get("FEntryTaxRate"),procurementValues.get("FApplicationOrgId"), procurementValues.get("FApplicationOrgId"), procurementValues.get("FApplicationOrgId"), zbValueTable.get("FBaseUnitId"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"));
			fEntityArray.add(JSONObject.fromObject(par));
		}

		String param = String.format(orderFormJson,date,procurementValues.get("FSuggestSupplierId"),procurementValues.get("FApplicationOrgId"));
		JSONObject json = JSONObject.fromObject(formJson);
		JSONObject jsonParam = JSONObject.fromObject(param);
		jsonParam.put("FPOOrderEntry", fEntityArray);
		json.put("Model", jsonParam);
		System.out.println(json.toString());
		JsonResult<K3cBase> kResult = k3cMaterialService.allSave("PUR_PurchaseOrder", json.toString());
		if ("ok".equals(kResult.getMsg())) {
			result.put("PUR_PurchaseOrder", kResult.getData().getNumber());
			//下推生成采购订单
			//添加生产的订单编号数组
			JSONArray jarray = new JSONArray();
			jarray.add(kResult.getData().getNumber());
					//下推到收料通知单
					JsonResult<K3cBase> purchaseOrderResult = push(jarray, "PUR_PurchaseOrder", "PUR_PurchaseOrder-PUR_ReceiveBill");
					System.out.println(purchaseOrderResult.toString());
					if ("ok".equals(purchaseOrderResult.getMsg())) {
						System.out.println("取收料子表id");
						JSONArray arrays = k3cMaterialService.getOrderIdList("PUR_ReceiveBill", "FDetailEntity_FEntryID", "FID='" + purchaseOrderResult.getData().getId() + "'");

						JSONObject fDetailEntityRe = JSONObject.fromObject(receiving);
						fDetailEntityRe.getJSONObject("Model").put("FID", purchaseOrderResult.getData().getId());
						JSONArray fdEntity = new JSONArray();
						for (Object id : arrays) {
							String idre = id.toString().substring(0, id.toString().length() - 1);
							idre = id.toString().substring(1, idre.toString().length());
							if (procurementValues.get("FApplicationOrgId").toString().startsWith("102")) {
								String str = String.format(fDetailEntity, idre, "1004", "GY");
								fdEntity.add(JSONObject.fromObject(str));
							} else if (procurementValues.get("FApplicationOrgId").toString().startsWith("101")) {
								String str = String.format(fDetailEntity, idre, "0409", "GY");
								fdEntity.add(JSONObject.fromObject(str));
							}
						}
						fDetailEntityRe.getJSONObject("Model").put("FDetailEntity", fdEntity);
						System.out.println("修改收料单仓库信息");
						k3cMaterialService.allSave("PUR_ReceiveBill", fDetailEntityRe.toString());

						result.put("PUR_ReceiveBill", purchaseOrderResult.getData().getNumber());
						JSONObject receiveBillJson = new JSONObject();
						JSONArray numbersReceiveBill = new JSONArray();
						numbersReceiveBill.add(purchaseOrderResult.getData().getNumber());
						receiveBillJson.put("Numbers", numbersReceiveBill);
						//提交收料通知单
						k3cMaterialService.submit("PUR_ReceiveBill", receiveBillJson.toString());
						//审核通知单
						JsonResult<K3cBase> receiveBillResult = k3cMaterialService.audit("PUR_ReceiveBill", receiveBillJson.toString());
						if ("ok".equals(receiveBillResult.getMsg())) {
							JSONArray dueNumbers = new JSONArray();
							dueNumbers.add(result.get("PUR_ReceiveBill") );
							System.out.println("下推应付单");
							JsonResult<K3cBase>   payableResult  = null;

							payableResult = push(dueNumbers, "PUR_ReceiveBill", "PUR_ReceiveBill-AP_Payable");
							if("ok".equals(payableResult.getMsg())) {
								System.out.println(payableResult.getData().getNumber());
								result.put("AP_Payable", payableResult.getData().getNumber());
								//修改应付单，再提交审核下推付款申请
								if (updatePayAble(procurementValues,zbBizObjects,payableResult.getData().getNumber())) {
									result.put("AP_Payable",procurementValues.get("invoiceNumber").toString());
								}
								JSONArray numbersPayable = new JSONArray();
								numbersPayable.add(procurementValues.get("invoiceNumber").toString());
								JSONObject jsonObjPayApp = new JSONObject();

								jsonObjPayApp.put("Numbers", numbersPayable);
								//提交付款申请单
								System.out.println("提交应付单");
								k3cMaterialService.submit("AP_Payable", jsonObjPayApp.toString());
								//审核付款申请单
								System.out.println("审核应付单");
								JsonResult<K3cBase> payAppResult = k3cMaterialService.audit("AP_Payable", jsonObjPayApp.toString());
								if ("ok".equals(payAppResult.getMsg())) {

									JSONArray paynumbers = new JSONArray();
									paynumbers.add(payAppResult.getData().getNumber());
									//下推付款申请单
									JsonResult<K3cBase> payDataResult = push(paynumbers, "AP_Payable", "AP_Payable-CN_PAYAPPLY");

									if("ok".equals(payDataResult.getMsg())) {
										result.put("CN_PAYAPPLY", payDataResult.getData().getNumber());
										if (updatePayApply(procurementValues,zbBizObjects,payDataResult.getData().getNumber())) {
											JSONObject payAppLy = new JSONObject();
											JSONArray jsonObjPayAppLy = new JSONArray();
											jsonObjPayAppLy.add(result.get("CN_PAYAPPLY"));
											payAppLy.put("Numbers", jsonObjPayAppLy);
											//提交付款申请单
											System.out.println("提交付款申请单");
											k3cMaterialService.submit("CN_PAYAPPLY", payAppLy.toString());
											//审核付款申请单
											System.out.println("审核付款申请单");
											JsonResult<K3cBase> payapplyResult = k3cMaterialService.audit("CN_PAYAPPLY", payAppLy.toString());
										}

									}
								}

							}

						}
					}
					return result;

			}
		return result;
	} catch (Exception e) {
		ErrorUtil.packageServerError(e);
		e.printStackTrace();
		try {
			return deleteOrder(result);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return result;


	}


}

	/**
	 * 根据主表，子表及单号修改付款申请单
	 * @param procurementValues
	 * @param zbBizObjects
	 * @param payApplyNumber
	 * @return
	 * @throws Exception
	 */
	public Boolean updatePayApply(HashMap<String, Object> procurementValues,BizObject[] zbBizObjects,String payApplyNumber) throws Exception {

		//先查询付款申请单id
		JSONArray payApplyIdArrays = k3cMaterialService.getOrderIdList("CN_PAYAPPLY", "FID,FPAYAPPLYENTRY_FEntryID", "FBillNo='" + payApplyNumber + "'");
		JSONArray ids = (JSONArray)payApplyIdArrays.get(0);

		JSONArray payApplyEntity = new JSONArray();
		String payApplyId = "";
		float payMoneyTotal = 0;
		for(int j = 0; j < zbBizObjects.length; j++) {
			payMoneyTotal += Float.valueOf(zbBizObjects[j].getValueTable().get("applPayMoney").toString());
		}

		String str = String.format(fPayApplyEntity,ids.get(1).toString(),zbBizObjects[0].getValueTable().get("costProject"),zbBizObjects[0].getValueTable().get("payType"),"","","",payMoneyTotal,zbBizObjects[0].getValueTable().get("Fproject"));
		payApplyEntity.add(JSONObject.fromObject(str));
		JSONObject fDetailEntity = JSONObject.fromObject(payAppOrder);
		fDetailEntity.getJSONObject("Model").put("FID", ids.get(0).toString());
		fDetailEntity.getJSONObject("Model").put("FPAYAPPLYENTRY", payApplyEntity);
		fDetailEntity.getJSONObject("Model").getJSONObject("FAPPLYORGID").put("FNumber", procurementValues.get("FApplicationOrgId").toString());
		fDetailEntity.put("IsAutoSubmitAndAudit",false);
		net.sf.json.JSONArray needUpDateFields = fDetailEntity.getJSONArray("NeedUpDateFields");
		needUpDateFields.add("FPAYAPPLYENTRY");
		needUpDateFields.add("FCOSTID");
		needUpDateFields.add("FSETTLETYPEID");
		needUpDateFields.add("FAPPLYAMOUNTFOR");
		needUpDateFields.add("F_WB_XM");
		net.sf.json.JSONArray needReturnFields = fDetailEntity.getJSONArray("NeedReturnFields");
		needReturnFields.add("FPAYAPPLYENTRY");
		needReturnFields.add("FCOSTID");
		needReturnFields.add("FSETTLETYPEID");
		needReturnFields.add("FAPPLYAMOUNTFOR");
		fDetailEntity.put("NeedUpDateFields", needUpDateFields);
		fDetailEntity.put("NeedReturnFields", needReturnFields);
		JsonResult<K3cBase> payApplyResult = k3cMaterialService.allSave("CN_PAYAPPLY", fDetailEntity.toString());
		if ("ok".equals(payApplyResult.getMsg())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据主表，子表信息，及单号修改应付单
	 * @param procurementValues
	 * @param zbBizObjects
	 * @param payableNumber
	 * @return
	 * @throws Exception
	 */
	public Boolean updatePayAble(HashMap<String, Object> procurementValues,BizObject[] zbBizObjects,String payableNumber) throws Exception {
		//先查询 应付单子表 id，为修改应付单准备
		JSONArray payableEntityIdarrays = k3cMaterialService.getOrderIdList("AP_Payable", "FID,FEntityDetail_FEntryID","FBillNo='"+ payableNumber +"'");
		//修改应付单
		String payableFid = "";
		JSONArray payableUpdateEntity = new JSONArray();
		for(int j = 0; j < zbBizObjects.length; j++) {
			JSONArray payableId = (JSONArray)payableEntityIdarrays.get(j);
			payableFid = payableId.get(0).toString();
			BizObject zbBiz = zbBizObjects[j];
			Map<String,Object> zbValueTable=zbBiz.getValueTable();
			String str = String.format(fEntityDetail,payableId.get(1).toString(),"x",zbValueTable.get("FPriceQty"),zbValueTable.get("FEntryTaxRate"),zbValueTable.get("FNoTaxAmountForD"),zbValueTable.get("FTAXAMOUNTFORD"),zbValueTable.get("FALLAMOUNTFORD"));
			payableUpdateEntity.add(JSONObject.fromObject(str));
		}
		JSONObject aPpayableEntity = JSONObject.fromObject(aPpayableOrder);
		aPpayableEntity.getJSONObject("Model").put("FID", payableFid);
		aPpayableEntity.getJSONObject("Model").put("FBillNo",procurementValues.get("invoiceNumber").toString());
		//aPpayableEntity.getJSONObject("Model").getJSONObject("FSUPPLIERID").put("FNumber", procurementValues.get("FSuggestSupplierId"));
		aPpayableEntity.getJSONObject("Model").getJSONObject("FSETTLEORGID").put("FNumber", procurementValues.get("FApplicationOrgId"));
		aPpayableEntity.getJSONObject("Model").put("FEntityDetail", payableUpdateEntity);
		aPpayableEntity.getJSONObject("Model").put("FISTAXINCOST", procurementValues.get("FISTAXINCOST"));
		aPpayableEntity.put("IsAutoSubmitAndAudit",false);
		net.sf.json.JSONArray needUpDateFields = aPpayableEntity.getJSONArray("NeedUpDateFields");
		needUpDateFields.add("FBillNo");
		needUpDateFields.add("FEntityDetail");
		//计价数量
		needUpDateFields.add("FPriceQty");
		//税率(%)
		needUpDateFields.add("FEntryTaxRate");
		//不含税金额
		needUpDateFields.add("FNoTaxAmountFor_D");
		//税额
		needUpDateFields.add("FTAXAMOUNTFOR_D");
		//价税合计
		needUpDateFields.add("FALLAMOUNTFOR_D");

		needUpDateFields.add("FISTAXINCOST");
		net.sf.json.JSONArray needReturnFields = aPpayableEntity.getJSONArray("NeedReturnFields");
		needUpDateFields.add("FBillNo");
		needReturnFields.add("FEntityDetail");
		needReturnFields.add("FPriceQty");
		needReturnFields.add("FEntryTaxRate");
		aPpayableEntity.put("NeedUpDateFields", needUpDateFields);
		aPpayableEntity.put("NeedReturnFields", needReturnFields);
		System.out.println(aPpayableEntity.toString());
		JsonResult<K3cBase> payableResult = k3cMaterialService.allSave("AP_Payable", aPpayableEntity.toString());
		if ("ok".equals(payableResult.getMsg())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据收料单号查询收料通知单信息
	 * @param receiveBillNum
	 * @return
	 */
	@RequestMapping(value = "/queryReceiveBill" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object queryReceiveBill(String receiveBillNum) {
		try {
			Map<String,Object> result = new LinkedHashMap();
			JSONArray receiveBillArray = k3cMaterialService.getOrderIdList("PUR_ReceiveBill", "FPurOrgId,F_WB_SQR,FSupplierId,FMaterialId,FMaterialName,FBaseUnitId,FBaseAPJoinQty,FPriceUnitQty,F_project,FDate,FOrderBillNo,FTaxPrice", "FBillNo='" +  receiveBillNum + "'");
			JSONArray receiveBillArrayFirst = (JSONArray)receiveBillArray.get(0);
			//申请组织
			String fPurOrgId = receiveBillArrayFirst.get(0).toString();
			JSONArray applOrg = k3cMaterialService.getOrderIdList("ORG_Organizations", "FNumber,FName","FOrgID = "+ fPurOrgId);
			result.put("ApplOrgId",fPurOrgId);
			result.put("FApplicationOrgId",applOrg.getJSONArray(0).get(0));
			result.put("ApplOrgText",applOrg.getJSONArray(0).get(1));
			//采购员
			String cgy = receiveBillArrayFirst.get(1).toString();
			JSONArray applPeo  = k3cMaterialService.getOrderIdList("BD_Empinfo", "FNumber,FName","FID  = "+ cgy);
			result.put("FApplicantId",applPeo.getJSONArray(0).get(0));
			result.put("ApplPeoText",applPeo.getJSONArray(0).get(1));
			//供应商
			String fSupplierId = receiveBillArrayFirst.get(2).toString();
			JSONArray gys  = k3cMaterialService.getOrderIdList("BD_Supplier", "FNumber,FName","FSupplierId  = "+ fSupplierId);
			result.put("FSuggestSupplierId",gys.getJSONArray(0).get(0));
			result.put("SupplierText",gys.getJSONArray(0).get(1));
			//申请日期
			result.put("FApplicationDate",receiveBillArrayFirst.get(9).toString().split("T")[0]);
			//采购订单单号
			result.put("procurementOrderNumber",receiveBillArrayFirst.get(10).toString());
			List zbList = new ArrayList();
			for (int i = 0; i < receiveBillArray.size(); i++) {
				JSONArray zbArray = receiveBillArray.getJSONArray(i);
				Map<String,String> zbData = new LinkedHashMap();

				//物料编码
				JSONArray materialArray  = k3cMaterialService.getOrderIdList("BD_MATERIAL", "FNumber","FMATERIALID   = "+ zbArray.get(3).toString());
				zbData.put("FMaterialId",materialArray.getJSONArray(0).get(0).toString());
				zbData.put("FMaterialName",zbArray.get(4).toString());
				//计量单位
				String fBaseUnitId = receiveBillArrayFirst.get(5).toString();
				JSONArray baseUnit  = k3cMaterialService.getOrderIdList("BD_UNIT", "FNumber","FUNITID  = "+ fBaseUnitId);
				zbData.put("FBaseUnitId",baseUnit.getJSONArray(0).get(0).toString());

				zbData.put("invoiceNumber",zbArray.get(6).toString());
				zbData.put("FReqQty",zbArray.get(7).toString());

				//项目
				String fProjectId = receiveBillArrayFirst.get(8).toString();
				JSONArray fProjectArray  = k3cMaterialService.getOrderIdList("kbba9e54046c04439918b3e186fce8d81", "FNumber,FName","FID  = "+ fProjectId);
				zbData.put("Fproject",fProjectArray.getJSONArray(0).get(0).toString());
				zbData.put("projectText",fProjectArray.getJSONArray(0).get(1).toString());
				//含税单价
				zbData.put("FTaxPrice",receiveBillArrayFirst.get(11).toString());
				zbList.add(zbData);
			}
			result.put("detail",zbList);


			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}



	/**
	 * 根据应付单号查询应付单信息
	 * @param payableNum
	 * @return
	 */
	@RequestMapping(value = "/queryPayable" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object queryPayable(String payableNum) {
		try {
			Map<String,Object> result = new LinkedHashMap();
			JSONArray payAbleArrays = k3cMaterialService.getOrderIdList("AP_Payable", "FSETTLEORGID,F_WB_SQR,FSUPPLIERID,FDATE,FAPPLYAMOUNT,F_XM,FALLAMOUNTFOR_D,FSourceBillNo,FORDERNUMBER,FTaxPrice","FBillNo='"+payableNum+"'");
			JSONArray payAbleArrayFirst = (JSONArray)payAbleArrays.get(0);
			//申请组织
			String fPurOrgId = payAbleArrayFirst.get(0).toString();
			JSONArray applOrg = k3cMaterialService.getOrderIdList("ORG_Organizations", "FNumber,FName","FOrgID = "+ fPurOrgId);
			result.put("ApplOrgId",fPurOrgId);
			result.put("FApplicationOrgId",applOrg.getJSONArray(0).get(0));
			result.put("ApplOrgText",applOrg.getJSONArray(0).get(1));
			//采购员
			String cgy = payAbleArrayFirst.get(1).toString();
			JSONArray applPeo  = k3cMaterialService.getOrderIdList("BD_Empinfo", "FNumber,FName","FID  = "+ cgy);
			result.put("FApplicantId",applPeo.getJSONArray(0).get(0));
			result.put("ApplPeoText",applPeo.getJSONArray(0).get(1));
			//供应商
			String fSupplierId = payAbleArrayFirst.get(2).toString();
			JSONArray gys  = k3cMaterialService.getOrderIdList("BD_Supplier", "FNumber,FName","FSupplierId  = "+ fSupplierId);
			result.put("FSuggestSupplierId",gys.getJSONArray(0).get(0));
			result.put("SupplierText",gys.getJSONArray(0).get(1));
			//申请日期
			result.put("FApplicationDate",payAbleArrayFirst.get(3).toString().split("T")[0]);
			//应付单关联付款金额
			result.put("FAPPLYAMOUNT",payAbleArrayFirst.get(4).toString());
			// 收料单号
			result.put("receivingNumber",payAbleArrayFirst.get(7).toString());
			// 采购订单号
			result.put("procurementOrderNumber",payAbleArrayFirst.get(8).toString());
			List zbList = new ArrayList();
			for (int i = 0; i < payAbleArrays.size(); i++) {
				JSONArray zbArray = payAbleArrays.getJSONArray(i);
				Map<String,String> zbData = new LinkedHashMap();
				//项目
				String fProjectId = zbArray.get(5).toString();
				JSONArray fProjectArray  = k3cMaterialService.getOrderIdList("kbba9e54046c04439918b3e186fce8d81", "FNumber,FName","FID  = "+ fProjectId);
				zbData.put("FWBXM",fProjectArray.getJSONArray(0).get(0).toString());
				zbData.put("projectMxText",fProjectArray.getJSONArray(0).get(1).toString());
				zbData.put("FALLAMOUNTFOR_D",zbArray.get(6).toString());
				//含税单价
				zbData.put("FTaxPrice",zbArray.get(9).toString());
				zbList.add(zbData);
			}
			result.put("detail",zbList);


			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}




	public  Map<String,String> purRequisition( String instanceId ,String formId ){

		Map<String, String> result = new LinkedHashMap<String, String>();
		result.put("STK_InStock", "无");
		result.put("PUR_ReceiveBill", "无");
		result.put("PUR_PurchaseOrder", "无");
		result.put("PUR_Requisition", "无");
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			@SuppressWarnings("unused")
			InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
			HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
			String date = format.format(procurementValues.get("FApplicationDate"));
			System.out.println(date);

			BizObject[] zbBizObjects = (BizObject[]) procurementValues.get("requestDetail");
			JSONArray fEntityArray = new JSONArray();

			for (int i = 0; i < zbBizObjects.length; i++) {
				Map<String, Object> zbValueTable = zbBizObjects[i].getValueTable();
				String par = String.format(fEntity, procurementValues.get("FApplicationOrgId"), zbValueTable.get("FMaterialId"), zbValueTable.get("FMaterialName"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"), procurementValues.get("FApplicationOrgId"), zbValueTable.get("FSupplierId"), zbValueTable.get("FSupplierId"), procurementValues.get("FApplicationOrgId"), zbValueTable.get("FTAXPRICE"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"), zbValueTable.get("FReqQty"));
				fEntityArray.add(JSONObject.fromObject(par));
			}

			String param = String.format(purchaseRequestParam, date, procurementValues.get("FApplicationOrgId"), procurementValues.get("Fproject"), procurementValues.get("FApplicantId"), procurementValues.get("FApplicationOrgId"), procurementValues.get("FMaterialId"), procurementValues.get("FMaterialName"), procurementValues.get("FReqQty"), procurementValues.get("FReqQty"), procurementValues.get("FApplicationOrgId"), procurementValues.get("FSuggestSupplierId"), procurementValues.get("FSuggestSupplierId"), procurementValues.get("FApplicationOrgId"), procurementValues.get("FTAXPRICE"), procurementValues.get("FTAXPRICE"), procurementValues.get("FReqQty"), procurementValues.get("FReqQty"), procurementValues.get("FReqQty"), procurementValues.get("FReqQty"), procurementValues.get("FReqQty"));
			JSONObject json = JSONObject.fromObject(formJson);
			JSONObject jsonParam = JSONObject.fromObject(param);
			jsonParam.put("FEntity", fEntityArray);
			json.put("Model", jsonParam);
			System.out.println(json.toString());
			JsonResult<K3cBase> kResult = k3cMaterialService.allSave(formId, json.toString());
			if ("ok".equals(kResult.getMsg())) {

				result.put("PUR_Requisition", kResult.getData().getNumber());
				//下推生成采购订单
				//添加生产的订单编号数组
				JSONArray jarray = new JSONArray();
				jarray.add(kResult.getData().getNumber());

				JsonResult<K3cBase> pushResult = push(jarray, formId, "PUR_Requisition-PUR_PurchaseOrder");
				System.out.println(pushResult.toString());
				if ("ok".equals(pushResult.getMsg())) {
					result.put("PUR_PurchaseOrder", pushResult.getData().getNumber());
					JSONObject purchaseOrderJson = new JSONObject();
					JSONArray numbersPurchaseOrder = new JSONArray();
					numbersPurchaseOrder.add(pushResult.getData().getNumber());
					purchaseOrderJson.put("Numbers", numbersPurchaseOrder);

					//提交采购订单
					k3cMaterialService.submit("PUR_PurchaseOrder", purchaseOrderJson.toString()); //提交
					//审核
					JsonResult<K3cBase> resultsubmit = k3cMaterialService.audit("PUR_PurchaseOrder", purchaseOrderJson.toString());
					if ("ok".equals(resultsubmit.getMsg())) {

						//下推到收料通知单
						JsonResult<K3cBase> purchaseOrderResult = push(numbersPurchaseOrder, "PUR_PurchaseOrder", "PUR_PurchaseOrder-PUR_ReceiveBill");

						System.out.println(purchaseOrderResult.toString());

						if ("ok".equals(purchaseOrderResult.getMsg())) {

							System.out.println("取收料子表id");
							JSONArray arrays = k3cMaterialService.getOrderIdList("PUR_ReceiveBill", "FDetailEntity_FEntryID", "FID='" + purchaseOrderResult.getData().getId() + "'");

							JSONObject fDetailEntityRe = JSONObject.fromObject(receiving);
							fDetailEntityRe.getJSONObject("Model").put("FID", purchaseOrderResult.getData().getId());
							JSONArray fdEntity = new JSONArray();
							for (Object id : arrays) {
								String idre = id.toString().substring(0, id.toString().length() - 1);
								idre = id.toString().substring(1, idre.toString().length());
								if (procurementValues.get("FApplicationOrgId").toString().startsWith("102")) {
									String str = String.format(fDetailEntity, idre, "1004", "GY");
									fdEntity.add(JSONObject.fromObject(str));
								} else if (procurementValues.get("FApplicationOrgId").toString().startsWith("101")) {
									String str = String.format(fDetailEntity, idre, "0409", "GY");
									fdEntity.add(JSONObject.fromObject(str));
								}
							}
							fDetailEntityRe.getJSONObject("Model").put("FDetailEntity", fdEntity);
							System.out.println("修改收料单仓库信息");
							k3cMaterialService.allSave("PUR_ReceiveBill", fDetailEntityRe.toString());

							result.put("PUR_ReceiveBill", purchaseOrderResult.getData().getNumber());
							JSONObject receiveBillJson = new JSONObject();
							JSONArray numbersReceiveBill = new JSONArray();
							numbersReceiveBill.add(purchaseOrderResult.getData().getNumber());
							receiveBillJson.put("Numbers", numbersReceiveBill);
							//提交收料通知单
							k3cMaterialService.submit("PUR_ReceiveBill", receiveBillJson.toString());
							//审核通知单
							JsonResult<K3cBase> receiveBillResult = k3cMaterialService.audit("PUR_ReceiveBill", receiveBillJson.toString());
							if ("ok".equals(receiveBillResult.getMsg())) {
								System.out.println("收料通知单审核成功");
							}
						}
						return result;
					}
				}
			}
			return result;
		} catch (Exception e) {
			ErrorUtil.packageServerError(e);
			e.printStackTrace();
			try {
				return deleteOrder(result);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return result;


		}


	}






	/**
	 *    保存采购申请下推至收料通知单
	 *    instanceId 实例id
	 *    formId 采购订单formId
	 * @return JsonResult
	 */
	@RequestMapping(value = "/save" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,String> save( String instanceId ,String formId ) {

		return purRequisition( instanceId , formId );

	}

	/**
	 *    保存采购订单下推至收料通知单
	 *    instanceId 实例id
	 *    formId 采购订单formId
	 * @return JsonResult
	 */
	@RequestMapping(value = "/saveOrder" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,String> saveOrder( String instanceId ,String detailCode) {

		return purRequisitionOrder( instanceId ,detailCode);

	}



  	@RequestMapping(value = "/saveCall" , produces = "application/json;charset=utf-8")
    @ResponseBody
    public void saveCall( String instanceId ,String formId ) throws Exception {

        InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
        Map<String,String>  orderIds = save(  instanceId , formId );

		IInstanceDataItem receivingNumber = instanceData.getItem("receivingNumber");
		IInstanceDataItem procurementNumber = instanceData.getItem("procurementNumber");
		IInstanceDataItem procurementOrderNumber = instanceData.getItem("procurementOrderNumber");

		receivingNumber.setValue(orderIds.get("PUR_ReceiveBill").toString());
		procurementOrderNumber.setValue(orderIds.get("PUR_PurchaseOrder").toString());
		procurementNumber.setValue(orderIds.get("PUR_Requisition").toString());
		instanceData.Submit();
      /*  PurchaseOrderApp purchaseOrderApp= new PurchaseOrderApp();
        purchaseOrderApp.setObjectId(bizObjectId);
        purchaseOrderApp.setProcurementNumber(orderIds.get("PUR_Requisition").toString());
        purchaseOrderApp.setProcurementOrderNumber(orderIds.get("PUR_PurchaseOrder").toString());
        purchaseOrderApp.setReceivingNumber(orderIds.get("PUR_ReceiveBill").toString());
      String sql = SqlUtils.genUpdateSql(  "I_purchaseOrderApp",   purchaseOrderApp,  "ObjectId");
      System.out.println(sql);
      int i=SqlUtils.doNoQuery( sql);
      System.out.println(i);*/

    }

	/**
	 * 生成采购订单，下推至收料
	 * @param instanceId
	 * @param detailCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveCallFromOrder" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public void saveCallFromOrder( String instanceId ,String detailCode) throws Exception {

		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		Map<String,String>  orderIds = saveOrder(instanceId ,detailCode);
		IInstanceDataItem cNPAYAPPLYNumber = instanceData.getItem("CNPAYAPPLY");
		IInstanceDataItem aPPayableNumber = instanceData.getItem("APPayable");
		IInstanceDataItem receivingNumber = instanceData.getItem("receivingNumber");
		IInstanceDataItem procurementOrderNumber = instanceData.getItem("procurementOrderNumber");

		cNPAYAPPLYNumber.setValue(orderIds.get("CN_PAYAPPLY").toString());
		aPPayableNumber.setValue(orderIds.get("AP_Payable").toString());
		receivingNumber.setValue(orderIds.get("PUR_ReceiveBill").toString());
		procurementOrderNumber.setValue(orderIds.get("PUR_PurchaseOrder").toString());
		instanceData.Submit();
	}


	/**
	 *  从收料 下推 直至 付款申请
	 * @param instanceId
	 * @param detailCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/callFromReceiveBill" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public void callFromReceiveBill( String instanceId ,String detailCode) throws Exception {

		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		Map<String,String>  orderIds = pushFromReceiveBill(instanceId,detailCode);
		IInstanceDataItem cNPAYAPPLYNumber = instanceData.getItem("CNPAYAPPLY");
		IInstanceDataItem aPPayableNumber = instanceData.getItem("APPayable");

		cNPAYAPPLYNumber.setValue(orderIds.get("CN_PAYAPPLY").toString());
		aPPayableNumber.setValue(orderIds.get("AP_Payable").toString());
		instanceData.Submit();
	}

	public  Map<String,String> pushFromReceiveBill( String instanceId,String detailCode) {

		Map<String, String> result = new LinkedHashMap<String, String>();
		result.put("CN_PAYAPPLY", "无");
		result.put("AP_Payable", "无");
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			@SuppressWarnings("unused")
			InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
			HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
			String date = format.format(procurementValues.get("FApplicationDate"));
			System.out.println(date);

			BizObject[] zbBizObjects = (BizObject[]) procurementValues.get(detailCode);
			JSONArray dueNumbers = new JSONArray();
			dueNumbers.add(procurementValues.get("receivingNumber"));
			System.out.println("下推应付单");
			JsonResult<K3cBase> payableResult = null;
			payableResult = push(dueNumbers, "PUR_ReceiveBill", "PUR_ReceiveBill-AP_Payable");
			if ("ok".equals(payableResult.getMsg())) {
				System.out.println(payableResult.getData().getNumber());
				result.put("AP_Payable", payableResult.getData().getNumber());
				//修改应付单，再提交审核下推付款申请
				if (updatePayAble(procurementValues, zbBizObjects, payableResult.getData().getNumber())) {
					result.put("AP_Payable", procurementValues.get("invoiceNumber").toString());
				}
				JSONArray numbersPayAble = new JSONArray();
				numbersPayAble.add(procurementValues.get("invoiceNumber").toString());
				JSONObject jsonObjPayApp = new JSONObject();

				jsonObjPayApp.put("Numbers", numbersPayAble);
				//提交付款申请单
				System.out.println("提交应付单");
				k3cMaterialService.submit("AP_Payable", jsonObjPayApp.toString());
				//审核付款申请单
				System.out.println("审核应付单");
				JsonResult<K3cBase> payAppResult = k3cMaterialService.audit("AP_Payable", jsonObjPayApp.toString());
				if ("ok".equals(payAppResult.getMsg())) {
					JSONArray paynumbers = new JSONArray();
					paynumbers.add(payAppResult.getData().getNumber());
					//下推付款申请单
					JsonResult<K3cBase> payDataResult = push(paynumbers, "AP_Payable", "AP_Payable-CN_PAYAPPLY");

					if ("ok".equals(payDataResult.getMsg())) {
						result.put("CN_PAYAPPLY", payDataResult.getData().getNumber());
						if (updatePayApply(procurementValues, zbBizObjects, payDataResult.getData().getNumber())) {
							JSONObject payAppLy = new JSONObject();
							JSONArray jsonObjPayAppLy = new JSONArray();
							jsonObjPayAppLy.add(result.get("CN_PAYAPPLY"));
							payAppLy.put("Numbers", jsonObjPayAppLy);
							//提交付款申请单
							System.out.println("提交付款申请单");
							k3cMaterialService.submit("CN_PAYAPPLY", payAppLy.toString()); //提交
							//审核付款申请单
							System.out.println("审核付款申请单");
							JsonResult<K3cBase> payapplyResult = k3cMaterialService.audit("CN_PAYAPPLY", payAppLy.toString());
						}

					}

				}
				return result;

			}
			return result;
		} catch (Exception e) {
			ErrorUtil.packageServerError(e);
			e.printStackTrace();
			try {
				return deleteOrder(result);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return result;
		}
	}


	/**
	 *  从应付 下推 直至 付款申请
	 * @param instanceId
	 * @param detailCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/callFromPayAble" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public void callFromPayAble( String instanceId ,String detailCode) throws Exception {

		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		Map<String,String>  orderIds = pushFromPayAble(instanceId,detailCode);
		IInstanceDataItem cNPAYAPPLYNumber = instanceData.getItem("CNPAYAPPLY");

		cNPAYAPPLYNumber.setValue(orderIds.get("CN_PAYAPPLY").toString());
		instanceData.Submit();
	}

	public  Map<String,String> pushFromPayAble( String instanceId,String detailCode) {

		Map<String, String> result = new LinkedHashMap<>();
		result.put("CN_PAYAPPLY", "无");
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			@SuppressWarnings("unused")
			InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
			HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
			String date = format.format(procurementValues.get("FApplicationDate"));
			System.out.println(date);

			        BizObject[] zbBizObjects = (BizObject[]) procurementValues.get(detailCode);

					JSONArray paynumbers = new JSONArray();
					paynumbers.add(procurementValues.get("APPayable"));
					//下推付款申请单
					JsonResult<K3cBase> payDataResult = push(paynumbers, "AP_Payable", "AP_Payable-CN_PAYAPPLY");
					if ("ok".equals(payDataResult.getMsg())) {
						result.put("CN_PAYAPPLY", payDataResult.getData().getNumber());
						if (updatePayApply(procurementValues, zbBizObjects, payDataResult.getData().getNumber())) {
							JSONObject payAppLy = new JSONObject();
							JSONArray jsonObjPayAppLy = new JSONArray();
							jsonObjPayAppLy.add(result.get("CN_PAYAPPLY"));
							payAppLy.put("Numbers", jsonObjPayAppLy);
							//提交付款申请单
							System.out.println("提交付款申请单");
							k3cMaterialService.submit("CN_PAYAPPLY", payAppLy.toString()); //提交
							//审核付款申请单
							System.out.println("审核付款申请单");
							JsonResult<K3cBase> payapplyResult = k3cMaterialService.audit("CN_PAYAPPLY", payAppLy.toString());
						}

				}
				return result;

		} catch (Exception e) {
			ErrorUtil.packageServerError(e);
			e.printStackTrace();
			try {
				return deleteOrder(result);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return result;
		}
	}


    @RequestMapping(value = "/saveProcurementsCall" , produces = "application/json;charset=utf-8")
    @ResponseBody
    public void saveProcurementsCall( String instanceId ,String formId ) throws Exception {

        InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
        Map<String,String>  orderIds = saveProcurements(  instanceId , formId );
        String bizObjectId = instanceData.getInstanceContext().getBizObjectId();
		IInstanceDataItem procurementPushNumber = instanceData.getItem("procurementPushNumber");
		IInstanceDataItem receivingNumber = instanceData.getItem("receivingNumber");
		IInstanceDataItem procurementNumber = instanceData.getItem("procurementNumber");
		IInstanceDataItem procurementOrderNumber = instanceData.getItem("procurementOrderNumber");
		procurementPushNumber.setValue(orderIds.get("STK_InStock").toString());
		receivingNumber.setValue(orderIds.get("PUR_ReceiveBill").toString());
		procurementOrderNumber.setValue(orderIds.get("PUR_PurchaseOrder").toString());
		procurementNumber.setValue(orderIds.get("PUR_Requisition").toString());
        instanceData.Submit();
       /* PurchaseOrderApp purchaseOrderApp= new PurchaseOrderApp();
        purchaseOrderApp.setObjectId(bizObjectId);
        purchaseOrderApp.setProcurementNumber(orderIds.get("PUR_Requisition").toString());
        purchaseOrderApp.setProcurementOrderNumber(orderIds.get("PUR_PurchaseOrder").toString());
        purchaseOrderApp.setReceivingNumber(orderIds.get("PUR_ReceiveBill").toString());
        purchaseOrderApp.setProcurementPushNumber(orderIds.get("STK_InStock").toString());
      String sql = SqlUtils.genUpdateSql(  "I_purchaseOrderApp",   purchaseOrderApp,  "ObjectId"    );
		int i =  SqlUtils.doNoQuery( sql);*/


    }

    /**
     *    保存采购订单下推至收料通知单(箱便分支流程)
 *    instanceId 实例id
 *    formId 采购订单formId
 * @return JsonResult
 */
    @RequestMapping(value = "/saveProcurements", produces = "application/json;charset=utf-8")
    @ResponseBody
public Map<String,String> saveProcurements(String instanceId , String formId ) {

		Map<String,String> result = purRequisition(instanceId ,formId);

		                 if(result!=null && !"反审核删除成功".equals(result.get("PUR_ReceiveBill")) && !"无".equals(result.get("PUR_ReceiveBill"))){
							 try {
								 JSONObject receiveBillJson = new JSONObject();
								 JSONArray numbersReceiveBill = new JSONArray();
								 numbersReceiveBill.add(result.get("PUR_ReceiveBill"));
								 receiveBillJson.put("Numbers", numbersReceiveBill);
                        	 //入库
                              JsonResult<K3cBase>  stkInStock =  push(numbersReceiveBill,"PUR_ReceiveBill", "PUR_ReceiveBill-STK_InStock");
                              if("ok".equals(stkInStock.getMsg())) {
                            	  result.put("STK_InStock", stkInStock.getData().getNumber());
                            	  JSONObject stkInStockJson = new JSONObject();
                        		  JSONArray numbersStkInStock = new JSONArray();
								  numbersStkInStock.add( stkInStock.getData().getNumber());
                        		 //提交入库
                        		  System.out.println("提交入库");
								  stkInStockJson.put("Numbers", numbersStkInStock);
                            	  k3cMaterialService.submit("STK_InStock", stkInStockJson.toString()); //提交
                            	  System.out.println("审核入库");
								  k3cMaterialService.audit("STK_InStock", stkInStockJson.toString());//审核入库单

							  }
							 } catch (Exception e) {
								 e.printStackTrace();
								 return deleteOrder(result);
							 }
                          }
                          return result;
                	 }


    /**
     * 组织查询
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getOrganizationList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getOrganizationList(String searchCode) {
        try {
            return k3cMaterialService.getNormalList("ORG_Organizations", "FNumber,FName,FOrgID","FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }


    /**
     * 用户查询
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getUserList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getUserList(String searchCode) {
        try {
            return k3cMaterialService.getNormalList("BD_Empinfo", "FNumber,FName","FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }

    /**
     * 项目查询
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getProjectList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getProjectList(String searchCode) {
        try {
            return k3cMaterialService.getNormalList("kbba9e54046c04439918b3e186fce8d81", "FNumber,FName","FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }


    /**
	 * 供应商查询
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getSupplierList", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getSupplierList(String searchCode,String fUseOrgId) {
		try {
			return k3cMaterialService.getNormalList("BD_Supplier", "FNumber,FName","  FUseOrgId = '"+fUseOrgId+"' and  ( FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%') and FDocumentStatus  =  'C'");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}

	/**
	 * 供应商银行信息查询
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getSupplierBackInfo", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getSupplierBackInfo(@RequestParam(value="FNumber",required=false) String fNumber, @RequestParam(value="FUseOrgId",required=false) String fUseOrgId) {
		try {
			return k3cMaterialService.getNormalList("BD_Supplier", "FBankCode,FBankHolder,FOpenBankName","  FUseOrgId = '"+ fUseOrgId +"' and   FNumber ='"+ fNumber +"'");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}


	/**
	 * 客户银行信息查询
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getCustomerBackInfo", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getCustomerBackInfo(@RequestParam(value="FNumber",required=false) String fNumber, @RequestParam(value="FUseOrgId",required=false) String fUseOrgId) {
		try {
			return k3cMaterialService.getNormalList("BD_Customer", "FBankCode,FACCOUNTNAME,FOPENBANKNAME ","  FUseOrgId = '"+ fUseOrgId +"' and   FNumber ='"+ fNumber +"'");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}

	/**
	 * 费用项目查询
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getCostProjectList", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getCostProjectList(String searchCode) {
		try {
			return k3cMaterialService.getNormalList("BD_Expense", "FNumber,FName","FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%'");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}


	/**
	 * 收付款用途查询
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getPayUseList", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getPayUseList(String searchCode) {
		try {
			return k3cMaterialService.getNormalList("CN_RECPAYPURPOSE", "FNumber,FName","FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%'");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}

    /**
     * 通用查询
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getNormalList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getNormalList(String formId,String searchCode,@RequestParam(value="FUseOrgId",required=false) String fUseOrgId) {
        try {
            return k3cMaterialService.getNormalList(formId, "FNumber,FName","   FUseOrgId = '"+ fUseOrgId +"' and  ( FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%')  and FDocumentStatus  =  'C'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }



    /**
     * 物料信息查询
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getMaterialInfoList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getMaterialInfoList(String searchCode,@RequestParam(value="OrguId",required=false) String orguId) {
        try {
            return k3cMaterialService.getNormalList("BD_MATERIAL", "FNumber,FName,FSpecification","FUSEORGID = '"+ orguId +"' and ( FNumber like '%"+searchCode+"%' or FName like '%"+searchCode+"%' or FSpecification like '%"+searchCode+"%')");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }


    /**
     *  收料通知单 单号查询  查询内容都是 已审核 未关闭的
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getReceiveBillNumList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getReceiveBillNumList(String searchCode) {
        try {
            return k3cMaterialService.getNormalList("PUR_ReceiveBill", "FBillNo,FDocumentStatus","  FDocumentStatus='C' and  FCloseStatus='A' and FBillNo like '%"+searchCode+"%'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }


    /**
     *  采购入库单 单号查询  查询内容都是 已审核 未关闭的
     *
     * @return JsonResult
     */
    @RequestMapping(value = "/getInStockNumList", produces = "application/json;charset=utf-8")
    @ResponseBody
    public JsonResult getInStockNumList(String searchCode) {
        try {
            return k3cMaterialService.getNormalList("STK_InStock", "FBillNo,FDocumentStatus","  FDocumentStatus='C'  and FBillNo like '%"+searchCode+"%'");
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorUtil.packageServerError(e);
        }
    }



	/**
	 *  应付单查询 查询内容都是 已审核 未关闭的
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/getInAppOrderNumList", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult getInAppOrderNumList(String searchCode) {
		try {
			return k3cMaterialService.getNormalList("AP_Payable", "FBillNo,FDocumentStatus","  FDocumentStatus='C'  and FBillNo like '%"+searchCode+"%' and FPAYAMOUNTFOR > FAPPLYAMOUNT");
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
	}

	/**
	 * 发票号 及应付单号查重
	 *
	 * @return JsonResult
	 */
	@RequestMapping(value = "/validateInvoiceNumber", produces = "application/json;charset=utf-8")
	@ResponseBody
	public Boolean validateInvoiceNumber(String invoiceNumber) {
		Boolean validateResult = false;
		try {
			JsonResult jsonResult =  k3cMaterialService.getNormalList("AP_Payable", "FBillNo,FDocumentStatus"," FBillNo = '"+invoiceNumber+"'");
			if (((ArrayList) jsonResult.getData()).size()==0) {
				validateResult = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return validateResult;
	}


	/**
	 * 根据 来源 和 单号  获取 生成的 应付单号
	 *  应对 收料或者入库下推 应付时 ， 业务方法超时导致的单号返回未接收问题
	 *  此方法 置于 修改应付单 节点 激活后
	 * @param instanceId  采购入库单号
	 * @return
	 */
	@RequestMapping(value = "/queryAPNumBySource", produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult queryAPNumBySource(String instanceId) {
		try {
			InstanceData instanceData = new InstanceData(getEngine(),instanceId,User.AdministratorID);
			String number = "";
			if ("收料通知单".equals((String)(instanceData.getItem("source").getValue()))) {
				number = (String)(instanceData.getItem("receivingNumber").getValue());
			} else {
				number = (String)(instanceData.getItem("STKInStock").getValue());
			}
			JsonResult<List<MaterialBase>> jsonResult = k3cMaterialService.getNormalList("AP_Payable", "FBillNo,FDocumentStatus","  FDocumentStatus= 'A' and FSourceBillNo='"+ number +"'"  );
			IInstanceDataItem aPPayable = instanceData.getItem("APPayable");
			aPPayable.setValue(jsonResult.getData().get(0).getCode());
			instanceData.Submit();
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorUtil.packageServerError(e);
		}
		return null;
	}


/**
 * 收料通知单开始下推至应付
 * @param receiveBillNumber 收料通知单单号
 * @param formId
 * @return
 * @throws Exception
 */
@RequestMapping(value="/dueBills",produces = "application/json;charset=utf-8")
@ResponseBody
public Map<String,String> dueBills( String receiveBillNumber ,String formId,String instanceId) throws Exception{

	     Map<String,String> numbers=new HashMap<String,String>();

	     try {

	     JSONArray dueNumbers= new JSONArray();
	     dueNumbers.add(receiveBillNumber );
	     System.out.println("下推应付单");
	     JsonResult<K3cBase>   result = null;

        	  result = push(dueNumbers, formId, formId+"-AP_Payable");
	     if("ok".equals(result.getMsg())) {
			 System.out.println(result.getData().getNumber());
	    	 numbers.put("AP_Payable", result.getData().getNumber());

	     }
	   	return numbers;
			} catch (Exception e) {
				 e.printStackTrace();
				return	deleteOrder(numbers);
			}

}

	@RequestMapping(value = "/dueBillsCall" , produces = "application/json;charset=utf-8")
	@ResponseBody
	public Object dueBillsCall( String receiveBillNumber ,String formId,String instanceId) throws Exception {

		//InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		return dueBills(   receiveBillNumber ,  formId,  instanceId);
//		String sql = "update I_payInstanceNew set APPayable = '"+ orderIds.get("AP_Payable") +"' where Objectid = '" + instanceData.getBizObject().getObjectID()+"'";
//		System.out.println("==updateSql===="+sql);
//		SqlUtils.doNoQuery(sql);
//		//IInstanceDataItem CNPAYAPPLY =  instanceData.getItem("CNPAYAPPLY");
//		IInstanceDataItem APPayable = instanceData.getItem("APPayable");
//		//IInstanceDataItem APPAYBILL = instanceData.getItem("APPAYBILL");
//		//CNPAYAPPLY.setValue(orderIds.get("CN_PAYAPPLY").toString());
//		APPayable.setValue(orderIds.get("AP_Payable").toString());
//		//APPAYBILL.setValue(orderIds.get("AP_PAYBILL").toString());
//		System.out.println("==Startwait===="+orderIds.get("AP_Payable").toString());
//		if(instanceData.Submit()){
//			System.out.println("==waitFinish===="+orderIds.get("AP_Payable").toString());
//			System.out.println("==APPayable===="+instanceData.getItem("APPayable").getValue().toString());
//			if (DotNetToJavaStringHelper.isNullOrEmpty(instanceData.getItem("APPayable").getValue().toString())) {
//				String sql = "update I_payInstanceNew set APPayable = "+ orderIds.get("AP_Payable").toString() +" where Objectid = " + instanceData.getBizObject();
//				System.out.println("==updateSql===="+sql);
//				SqlUtils.doNoQuery(sql);
//			}
//		}
	/*	PayInstanceNew payInstanceNew= new PayInstanceNew();
		payInstanceNew.setObjectId(bizObjectId);

		payInstanceNew.setAPPayable(orderIds.get("AP_Payable").toString());
		payInstanceNew.setAPPAYBILL(orderIds.get("AP_PAYBILL").toString());
		payInstanceNew.setCNPAYAPPLY(orderIds.get("CN_PAYAPPLY").toString());
		String sql = SqlUtils.genUpdateSql(  "I_payInstanceNew",   payInstanceNew,  "ObjectId"    );
		SqlUtils.doNoQuery(sql);*/

	}
	/**
	 * 查询采购申请单
	 * @param paymentRequestNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getPaymentRequest",produces = "application/json;charset=utf-8")
	@ResponseBody
	public  List<Map<String,Object>> getPaymentRequest(String paymentRequestNo,String instanceId) throws Exception {


		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();

		String  aPPayableNum = (String) procurementValues.get("APPayable");
		if (DotNetToJavaStringHelper.isNullOrEmpty(aPPayableNum)) {
			aPPayableNum  = (String) procurementValues.get("APPayableNum");
		}

		JSONArray aPPayable = k3cMaterialService.getOrderIdList("AP_Payable", "FID,FEntityPlan_FEntryID,FPAYAMOUNTFOR,FAPPLYAMOUNT", "FBillNo='" + aPPayableNum + "'");
		JSONArray arrays = k3cMaterialService.getOrderIdList("CN_PAYAPPLY", "FID,FPAYAPPLYENTRY_FEntryID,FCOSTID,FSETTLETYPEID,FAPPLYAMOUNTFOR,FAPPLYORGID,FMATERIALID ", "FBillNo='" + paymentRequestNo + "'");

		List<Map<String, Object>> list = new ArrayList();
		//取出查询出的结果数据做封装
		for (int i = 0; i < arrays.size(); i++) {
			Map<String, Object> result = new HashMap<String, Object>();
			String idre = arrays.get(0).toString().substring(0, arrays.get(0).toString().length() - 1);
			idre = arrays.get(0).toString().substring(1, idre.toString().length());
			String[] idres = idre.split(",");
			result.put("FID", idres[0]);
			//Map<String,Object> zbValueTable=new HashMap<String,Object>();
			result.put("FEntryID", idres[1]);
			result.put("costProject", idres[2]);
			result.put("payType", idres[3]);
			result.put("applPayMoney", idres[4]);


			result.put("FPAYAMOUNTFOR", aPPayable.getJSONArray(0).getString(2));
			result.put("FAPPLYAMOUNT", aPPayable.getJSONArray(0).getString(3));


			//根据组织id查询组织
			JSONArray arrayOrg = k3cMaterialService.getOrderIdList("ORG_Organizations", "FName,FNumber", "FOrgID=" + idres[5] + "");
			result.put("applUnit", arrayOrg.getJSONArray(0).get(1));
			list.add(result);

		}
		return list;
	}





	/**
	 * 查询应付单(收料流程)
	 * @param dealWithOrderNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/dealWithOrderPUR",produces = "application/json;charset=utf-8")
	@ResponseBody
	public  List<Map<String,Object>> dealWithOrder(String dealWithOrderNo,String receivingNumber,String instanceId ) throws Exception{

		InstanceData instanceData = null;
		HashMap<String, Object> procurementValues =null;
		if(instanceId != null) {

			instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
				  procurementValues = instanceData.getBizObject().getValueTable();

				}

		JSONArray arrays=k3cMaterialService.getOrderIdList("AP_Payable", "FID,FSUPPLIERID,FCURRENCYID,FSETTLEORGID,FEntityDetail_FEntryID,FTaxPrice,FMaterialName,F_WB_BaseProperty3,FMATERIALID,FPriceQty,FPrice,FEntryTaxRate,FNoTaxAmountFor_D,FTAXAMOUNTFOR_D,FALLAMOUNTFOR_D,FISTAXINCOST","FBillNo='"+dealWithOrderNo+"'");
		JSONArray shouLiao = null;
		if(instanceId==null) {
			  shouLiao = k3cMaterialService.getOrderIdList("PUR_ReceiveBill", "FID,FDetailEntity_FEntryID,FMaterialId,FBaseAPJoinQty,FPriceUnitQty,FActReceiveQty", "FBillNo='" + receivingNumber + "'");
		}else{
			  shouLiao = k3cMaterialService.getOrderIdList("PUR_ReceiveBill", "FID,FDetailEntity_FEntryID,FMaterialId,FBaseAPJoinQty,FPriceUnitQty,FActReceiveQty", "FBillNo='" + procurementValues.get("receivingNumber").toString() + "'");
		}
		List<Map<String,Object>> list=new ArrayList();

		//取出查询出的结果数据做封装
		for(int i=0;i<arrays.size();i++) {
			Map<String,Object> result=new HashMap<String,Object>();
			String idre = arrays.get(i).toString().substring(0, arrays.get(i).toString().length() - 1);
			idre = arrays.get(i).toString().substring(1, idre.toString().length());
			String[] idres = idre.split(",");
			result.put("FID", idres[0]);
			//Map<String,Object> zbValueTable=new HashMap<String,Object>();
			result.put("FEntryID", idres[4]);
			result.put("FTaxPrice", idres[5]);
			result.put("FMaterialName", idres[6]);
			result.put("F_WB_BaseProperty3", idres[7]);
			result.put("FPriceQty", idres[9]);
			result.put("FISTAXINCOST", idres[15]);
			result.put("FPrice", idres[10]);
			result.put("FEntryTaxRate",idres[11]);
			result.put("FNoTaxAmountFor_D", idres[12]);
			result.put("FTAXAMOUNTFOR_D",idres[13]);
			result.put("FALLAMOUNTFOR_D", idres[14]);
			for(int j=0;j<shouLiao.size();j++){
				if(shouLiao.getJSONArray(j).getString(2).equals(idres[8])){
					result.put("FBaseAPJoinQty", shouLiao.getJSONArray(j).getString(3));
					result.put("FPriceUnitQty",shouLiao.getJSONArray(j).getString(4));
					result.put("FMaterialId", shouLiao.getJSONArray(j).getString(2));
					result.put("FActReceiveQty", shouLiao.getJSONArray(j).getString(5));
				}

			}

			//根据组织id查询组织
			 JSONArray arrayOrg = k3cMaterialService.getOrderIdList("ORG_Organizations", "FNumber", "FOrgID=" + idres[3] + "");
			 result.put("FSETTLEORGID", arrayOrg.getJSONArray(0).get(0));
			JSONArray gys = k3cMaterialService.getOrderIdList("BD_Supplier", "FNumber","FSupplierId = "+ idres[1]);
			result.put("FSUPPLIERID", gys.getJSONArray(0).get(0));
			list.add(result);
		}

		return list;
	}





	/**
	 * 查询应付单(入库流程)
	 * @param dealWithOrderNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/dealWithOrderSTK",produces = "application/json;charset=utf-8")
	@ResponseBody
	public  List<Map<String,Object>> sTKInStockOrder(String dealWithOrderNo,String sTKInStock,String instanceId ) throws Exception{

		InstanceData instanceData = null;
		HashMap<String, Object> procurementValues =null;
		if(instanceId != null) {

			instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
			procurementValues = instanceData.getBizObject().getValueTable();

		}
		JSONArray arrays=k3cMaterialService.getOrderIdList("AP_Payable", "FID,FSUPPLIERID,FCURRENCYID,FSETTLEORGID,FISTAXINCOST,FEntityDetail_FEntryID,FTaxPrice,FMaterialName,F_WB_BaseProperty3,FMATERIALID,FPriceQty,FPrice,FEntryTaxRate,FNoTaxAmountFor_D,FTAXAMOUNTFOR_D,FALLAMOUNTFOR_D","FBillNo='"+dealWithOrderNo+"'");
		JSONArray ruKu=null;
		if(instanceId == null){
		     ruKu=k3cMaterialService.getOrderIdList("STK_InStock",  "FID,FInStockEntry_FEntryID,FMaterialId,FAPNotJoinQty,FStockBaseAPJoinQty,FRealQty","FBillNo='"+ sTKInStock +"'");
		}else{
			ruKu=k3cMaterialService.getOrderIdList("STK_InStock",  "FID,FInStockEntry_FEntryID,FMaterialId,FAPNotJoinQty,FStockBaseAPJoinQty,FRealQty","FBillNo='"+procurementValues.get("STKInStock").toString()+"'");
		}
		List<Map<String,Object>> list=new ArrayList();

		//取出查询出的结果数据做封装
		for(int i=0;i<arrays.size();i++) {
			Map<String,Object> result=new HashMap<>();
			String idre = arrays.get(i).toString().substring(0, arrays.get(i).toString().length() - 1);
			idre = arrays.get(i).toString().substring(1, idre.toString().length());
			String[] idres = idre.split(",");
			result.put("FID", idres[0]);
			//Map<String,Object> zbValueTable=new HashMap<String,Object>();
			result.put("FEntryID", idres[5]);
			result.put("FTaxPrice", idres[6]);
			result.put("FMaterialName", idres[7]);
			result.put("F_WB_BaseProperty3", idres[8]);
			result.put("FPriceQty", idres[10]);
			result.put("FISTAXINCOST", idres[4]);
			result.put("FPrice", idres[11]);
			result.put("FEntryTaxRate",idres[12]);
			result.put("FNoTaxAmountFor_D", idres[13]);
			result.put("FTAXAMOUNTFOR_D",idres[14]);
			result.put("FALLAMOUNTFOR_D", idres[15]);

			for(int j=0;j<ruKu.size();j++){
				 if(ruKu.getJSONArray(j).getString(2).equals(idres[9])){
					 result.put("FAPNotJoinQty", ruKu.getJSONArray(j).getString(3));
					 result.put("FRealQty",ruKu.getJSONArray(j).getString(5));
					 result.put("FStockBaseAPJoinQty", ruKu.getJSONArray(j).getString(4));
					 result.put("FMaterialId", ruKu.getJSONArray(j).getString(2));
				 }

			}

			//根据组织id查询组织
			JSONArray arrayOrg = k3cMaterialService.getOrderIdList("ORG_Organizations", "FNumber", "FOrgID=" + idres[3] + "");
			result.put("FSETTLEORGID", arrayOrg.getJSONArray(0).get(0));
			JSONArray gys = k3cMaterialService.getOrderIdList("BD_Supplier", "FNumber","FSupplierId = "+ idres[1]);
			result.put("FSUPPLIERID", gys.getJSONArray(0).get(0));
			list.add(result);
		}

		return list;
	}






	/**
	 * 修改应付单
	 * @param instanceId
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/updateDealWithOrder",produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,String> updateDealWithOrder(String instanceId) throws Exception {
		Map<String,String> numbers=new LinkedHashMap<String,String>();

		numbers.put("CN_PAYAPPLY", "无");
		numbers.put("AP_Payable", "无");
		try {

		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();


		BizObject[] zbBizObjects = (BizObject[]) procurementValues.get("dealWithDetail");
		JSONArray fdEntity = new JSONArray();
		String fSUPPLIERID = null;
		String fSETTLEORGID =null;
		for(BizObject zbBiz:zbBizObjects) {
			 Map<String,Object> zbValueTable=zbBiz.getValueTable();
			fSUPPLIERID = zbValueTable.get("FSUPPLIERID").toString();
			fSETTLEORGID = zbValueTable.get("FSETTLEORGID").toString();
			String str = String.format(fEntityDetail,zbValueTable.get("dealWithFEntryID").toString(),"x",zbValueTable.get("FPriceQty"),zbValueTable.get("FEntryTaxRate"),zbValueTable.get("FNoTaxAmountForD"),zbValueTable.get("FTAXAMOUNTFORD"),zbValueTable.get("FALLAMOUNTFORD"));
			fdEntity.add(JSONObject.fromObject(str));
		}
		JSONObject fDetailEntity = JSONObject.fromObject(aPpayableOrder);
		numbers.put("AP_Payable", procurementValues.get("APPayable").toString());
		fDetailEntity.getJSONObject("Model").put("FID", procurementValues.get("dealWithFId"));
		fDetailEntity.getJSONObject("Model").put("FBillNo",procurementValues.get("APPayable"));
		fDetailEntity.getJSONObject("Model").getJSONObject("FSUPPLIERID").put("FNumber",fSUPPLIERID);
		fDetailEntity.getJSONObject("Model").getJSONObject("FSETTLEORGID").put("FNumber",fSETTLEORGID);
		fDetailEntity.getJSONObject("Model").put("FEntityDetail", fdEntity);
		fDetailEntity.getJSONObject("Model").put("FISTAXINCOST", procurementValues.get("FISTAXINCOST"));
		fDetailEntity.put("IsAutoSubmitAndAudit",false);
		net.sf.json.JSONArray needUpDateFields = fDetailEntity.getJSONArray("NeedUpDateFields");
			needUpDateFields.add("FBillNo");
			needUpDateFields.add("FEntityDetail");
		//计价数量
			needUpDateFields.add("FPriceQty");
		//税率(%)
			needUpDateFields.add("FEntryTaxRate");
		//不含税金额
			needUpDateFields.add("FNoTaxAmountFor_D");
		//税额
			needUpDateFields.add("FTAXAMOUNTFOR_D");
		//价税合计
			needUpDateFields.add("FALLAMOUNTFOR_D");

			needUpDateFields.add("FISTAXINCOST");
		net.sf.json.JSONArray needReturnFields = fDetailEntity.getJSONArray("NeedReturnFields");
			needReturnFields.add("FBillNo");
			needReturnFields.add("FEntityDetail");
			needReturnFields.add("FPriceQty");
			needReturnFields.add("FEntryTaxRate");
		fDetailEntity.put("NeedUpDateFields", needUpDateFields);
		fDetailEntity.put("NeedReturnFields", needReturnFields);
		System.out.println(fDetailEntity.toString());
		JsonResult<K3cBase> receiveBillResult = k3cMaterialService.allSave("AP_Payable", fDetailEntity.toString());

		JSONObject jsonObjPayApp = new JSONObject();

		jsonObjPayApp.put("Numbers", receiveBillResult.getData().getNumber());
		//提交付款申请单
		System.out.println("提交应付单");
		k3cMaterialService.submit("AP_Payable", jsonObjPayApp.toString()); //提交
		//审核付款申请单
		System.out.println("审核应付单");
		JsonResult<K3cBase> payAppResult = k3cMaterialService.audit("AP_Payable", jsonObjPayApp.toString());
		if ("ok".equals(payAppResult.getMsg())) {

			JSONArray paynumbers = new JSONArray();
			paynumbers.add(receiveBillResult.getData().getNumber());
			//下推付款申请单
			JsonResult<K3cBase> payDataResult = push(paynumbers, "AP_Payable", "AP_Payable-CN_PAYAPPLY");

			if("ok".equals(payDataResult.getMsg())) {
				numbers.put("CN_PAYAPPLY", payDataResult.getData().getNumber());
				IInstanceDataItem cNPAYAPPLY =  instanceData.getItem("CNPAYAPPLY");
				cNPAYAPPLY.setValue(payDataResult.getData().getNumber());
				instanceData.Submit();

			}
		}
		} catch (Exception e) {
			ErrorUtil.packageServerError(e);
			e.printStackTrace();
			try {

			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return numbers;
	}


	/**
	 * 修改付款申请单
	 * @param instanceId
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/paymentRequestSave",produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,String> paymentRequestSave(String instanceId) throws Exception {
		Map<String,String> numbers=new LinkedHashMap<String,String>();
		try {
		numbers.put("AP_PAYBILL", "无");
		numbers.put("CN_PAYAPPLY", "无");
		numbers.put("AP_Payable", "无");
		InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
		HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
		BizObject[] zbBizObjects = (BizObject[]) procurementValues.get("applPayDetail");
		JSONArray fdEntity = new JSONArray();
		numbers.put("CN_PAYAPPLY", procurementValues.get("CNPAYAPPLY").toString() );
		numbers.put("AP_Payable", procurementValues.get("APPayable").toString());
		for(BizObject zbBiz:zbBizObjects) {
			 Map<String,Object> zbValueTable=zbBiz.getValueTable();
			String str = String.format(fPayApplyEntity,zbValueTable.get("applyFid").toString(),zbValueTable.get("costProject"),zbValueTable.get("payType"),"","","",zbValueTable.get("applPayMoney"),zbValueTable.get("FWBXM"));
			fdEntity.add(JSONObject.fromObject(str));
		}
		JSONObject fDetailEntity = JSONObject.fromObject(payAppOrder);
		fDetailEntity.getJSONObject("Model").put("FID", procurementValues.get("FID"));
		fDetailEntity.getJSONObject("Model").put("FPAYAPPLYENTRY", fdEntity);
		fDetailEntity.getJSONObject("Model").getJSONObject("FAPPLYORGID").put("FNumber", procurementValues.get("applUnit").toString());
		fDetailEntity.put("IsAutoSubmitAndAudit",false);
		net.sf.json.JSONArray needUpDateFields = fDetailEntity.getJSONArray("NeedUpDateFields");
			needUpDateFields.add("FPAYAPPLYENTRY");
			needUpDateFields.add("FCOSTID");
			needUpDateFields.add("FSETTLETYPEID");
			needUpDateFields.add("FAPPLYAMOUNTFOR");
			needUpDateFields.add("F_WB_XM");

		net.sf.json.JSONArray needReturnFields = fDetailEntity.getJSONArray("NeedReturnFields");
			needReturnFields.add("FPAYAPPLYENTRY");
			needReturnFields.add("FCOSTID");
			needReturnFields.add("FSETTLETYPEID");
			needReturnFields.add("FAPPLYAMOUNTFOR");
		fDetailEntity.put("NeedUpDateFields", needUpDateFields);
		fDetailEntity.put("NeedReturnFields", needReturnFields);
		JsonResult<K3cBase> receiveBillResult = k3cMaterialService.allSave("CN_PAYAPPLY", fDetailEntity.toString());
		JSONObject jsonObjPayApp = new JSONObject();
		jsonObjPayApp.put("Numbers", receiveBillResult.getData().getNumber());
		//提交付款申请单
		System.out.println("提交付款申请单");
		k3cMaterialService.submit("CN_PAYAPPLY", jsonObjPayApp.toString()); //提交
		//审核付款申请单
		System.out.println("审核付款申请单");
		JsonResult<K3cBase> payAppResult = k3cMaterialService.audit("CN_PAYAPPLY", jsonObjPayApp.toString());
		if ("ok".equals(payAppResult.getMsg())) {

		}
	} catch (Exception e) {
		ErrorUtil.packageServerError(e);
		e.printStackTrace();
			deleteOrder(numbers);
	}
		return numbers;
	}



	/**
	 * 应付单号直接下推
	 * @param instanceId
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/pushDealWithOrder",produces = "application/json;charset=utf-8")
	@ResponseBody
	public Map<String,String> pushDealWithOrder(String dealWithOrderNo,String instanceId) throws Exception {
		Map<String,String> numbers=new LinkedHashMap<String,String>();

		numbers.put("CN_PAYAPPLY", "无");
		numbers.put("AP_Payable", "无");

        InstanceData instanceData = null;
        instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

		JSONArray paynumbers = new JSONArray();
		paynumbers.add(dealWithOrderNo);
		//下推付款申请单
		JsonResult<K3cBase> payDataResult = push(paynumbers, "AP_Payable", "AP_Payable-CN_PAYAPPLY");

		if("ok".equals(payDataResult.getMsg())) {
			numbers.put("CN_PAYAPPLY", payDataResult.getData().getNumber());

		}

		return numbers;
	}

	/**
	 * 父流程附件下推
	 * @param instanceId
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/pushAttachment",produces = "application/json;charset=utf-8")
	@ResponseBody
	public void pushAttachment(String source,String instanceId) throws Exception {
		System.out.println("source============"+source+"====instanceId==============="+instanceId);
		if ("收料通知单".equals(source) || "采购入库单".equals(source)) {
			InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
			//获取父流程id
			String parentInstanceId = instanceData.getInstanceContext().getParentInstanceID();
			if (!DotNetToJavaStringHelper.isNullOrEmpty(parentInstanceId)) {
				////获取子流程附件
				List<AttachmentHeader> headers = AppUtility.getEngine().getBizObjectManager().QueryAttachment(
						instanceData.getSchemaCode(),instanceData.getBizObject().getObjectID(), "accessory", BoolMatchValue.True, "");
				//子流程没有附件才去父流程附件
				if (headers.size()==0) {
					InstanceData parentInstanceData = new InstanceData(getEngine(), parentInstanceId, User.AdministratorID);
					//获取父流程附件
					List<AttachmentHeader> parentHeaders = AppUtility.getEngine().getBizObjectManager().QueryAttachment(
							parentInstanceData.getSchemaCode(),parentInstanceData.getBizObject().getObjectID(), "upFile", BoolMatchValue.True, "");
					for (int i = 0 ; i < parentHeaders.size(); i++) {
						AttachmentHeader header = parentHeaders.get(i);
						Attachment parentAttachment = AppUtility.getEngine().getBizObjectManager().GetAttachment(User.AdministratorID,
								parentInstanceData.getSchemaCode(),
								parentInstanceData.getBizObject().getObjectID(),
								header.getObjectID());
						Attachment attachment = new Attachment();
						attachment.setObjectID(UUID.randomUUID().toString());
						attachment.setContent(parentAttachment.getContent());
						attachment.setContentType(parentAttachment.getContentType());
						attachment.setCreatedBy(instanceData.getInstanceContext().getOriginator());
						attachment.setCreatedTime(new Date());
						attachment.setFileName(parentAttachment.getFileName());
						attachment.setLastVersion(true);
						attachment.setModifiedTime(new Date());
						attachment.setBizObjectSchemaCode(instanceData.getSchemaCode());
						attachment.setContentLength(parentAttachment.getContentLength());
						attachment.setBizObjectId(instanceData.getBizObject().getObjectID());
						attachment.setDataField("accessory");
						getEngine().getBizObjectManager().AddAttachment(attachment);
					}
				}

			}
		}


	}


}